<?php

require_once 'MainPageWidget.php';
class PopularItemsWidget extends MainPageWidget
{
	public $title = 'Популярные записи';

	public $pi_count = 5; // сколько последних выводить

	public function Render()
	{
		// запросим несколько последних итемсов с кучей разной информации про комментарии
		$this->ctx->rh->UseClass('RL_CyrDate');

		foreach($this->getParam("tdis") as $n=>$tdi_oid) {
			if (is_numeric($tdi_oid)) {
				$_tdi_where = "afeed.tdi_oid=".$tdi_oid;
				$_tdi_w[] = $_tdi_where;
			}
		}

		if (count($_tdi_w) == 0) {
			//			$this->content['title'] = 'Раздел не выбран.';
			$this->tdi_not_found = 1;
			return $this;
		}

		// здесь стояла задача выбрать N записей которые содержат наибольшее кол-во комментариев,
		// причем эти записи должны быть созданы в течении недели с текущего момента

		$ors = new DBStoreResult($this->store,
				$this->store->query("
				SELECT
					afeed.title as item_title,
					afeed.oid as item_oid,
					tdi.color as tdi_color,
					(
		                SELECT COUNT(*)
		                FROM store_class_comment AS C1
		                WHERE C1.item_oid = afeed.oid AND C1.is_deleted = 0
	              	) AS comments_count
					FROM store_objects AS objs
					INNER JOIN store_class_allfeed AS afeed ON afeed.oid = objs.oid AND afeed.is_deleted=0
					LEFT JOIN (
					            SELECT comments.oid, comments.text, comments.item_oid, comments.posted_by_id, O.ctime as ctime
					            FROM store_class_comment AS comments
					            INNER JOIN store_objects AS O
					            ON comments.oid = O.oid
					            WHERE O.ctime = (
					              SELECT MAX(O2.ctime)
					              FROM store_class_comment AS comments2
					              INNER JOIN store_objects AS O2 ON comments2.oid = O2.oid AND comments2.is_deleted=0
					              WHERE comments2.item_oid = comments.item_oid
					            ) AND O.is_deleted = 0) AS comments ON comments.item_oid = afeed.oid
					INNER JOIN store_class_tdi tdi ON afeed.tdi_oid = tdi.oid
					INNER JOIN t_acl_tree tat ON tat.id_object = objs.oid AND tat.is_deleted = 0
					WHERE ".($_tdi_w ? " (".implode(" OR ", $_tdi_w).")" :"" )."
					AND objs.ctime BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
					ORDER BY (SELECT COUNT(*) FROM store_class_comment AS C1 WHERE C1.item_oid = afeed.oid AND C1.is_deleted = 0) DESC, item_title ASC
					LIMIT ".$this->getParam("items_count", 3)));

		while ($obj = $ors->next()) {
			$row = $ors->rs->current();
			$item = $row;
			$items[] = $item;
			unset($item);
		}

		$content['items'] = $items;
		$content['title'] = $this->getParam("title");
		$this->content = $content;
		return $this;
	}

}

